<template>
  <div class="address-list">
    <van-nav-bar
      title="地址列表"
      left-text="返回"
      @click-left="back"
      left-arrow
    />
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      default-tag-text="默认"
      :switchable="false"
      @add="add"
      @edit="edit"
    />
  </div>
</template>

<script>
import "../assets/less/addressList.less";
export default {
  name: "AddressList",
  data() {
    return {
      chosenAddressId: "1",
      list: [],
    };
  },

  created() {
    this.getAddressList();
  },

  methods: {
    back() {
      this.$router.back();
    },

    // 新增地址
    add() {
      this.$router.push({ name: "Address" });
    },

    // 编辑地址
    edit({aid}) {
      this.$router.push({name: 'Address', params: {aid}});
    },

    // 获取新增地址
    getAddressList() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        console.log("浏览器token不存在");
        return this.$router.push({ name: "Login" });
      }

      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });

      this.axios({
        method: "GET",
        url: this.baseURL + "/findAddress",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((response) => {
          this.$toast.clear();
          // console.log(response);

          if (response.data.code === 700) {
            this.$toast({
              message: response.date.msg,
              forbidClick: true,
              duration: 1000,
            });
            this.$router.push({ name: "Login" });
          }

          if (response.data.code === 20000) {
            response.data.result.forEach(v => {
              v.address = `${v.province}${v.city}${v.county}${v.addressDetail}`;
              v.isDefault = !!v.isDefault;
            })
            this.list = response.data.result;
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.error(err);
        });
    },
  },
};
</script>
